package com.atguigu.srb.core.service.impl;

import com.atguigu.srb.core.enums.BorrowInfoStatusEnum;
import com.atguigu.srb.core.enums.DictEnum;
import com.atguigu.srb.core.mapper.BorrowerMapper;
import com.atguigu.srb.core.mapper.IntegralGradeMapper;
import com.atguigu.srb.core.mapper.UserInfoMapper;
import com.atguigu.srb.core.pojo.entity.*;
import com.atguigu.srb.core.mapper.BorrowInfoMapper;
import com.atguigu.srb.core.pojo.vo.BorrowInfoApprovalVO;
import com.atguigu.srb.core.pojo.vo.BorrowerDetailVO;
import com.atguigu.srb.core.service.BorrowInfoService;
import com.atguigu.srb.core.service.BorrowerService;
import com.atguigu.srb.core.service.DictService;
import com.atguigu.srb.core.service.LendService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 借款信息表 服务实现类
 * </p>
 *
 * @author AtLong
 * @since 2022-06-11
 */
@Transactional(rollbackFor = Exception.class)
@Service
@Slf4j
public class BorrowInfoServiceImpl extends ServiceImpl<BorrowInfoMapper, BorrowInfo> implements BorrowInfoService {
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private IntegralGradeMapper integralGradeMapper;
    @Resource
    private BorrowInfoMapper borrowInfoMapper;
    @Resource
    private BorrowerMapper borrowerMapper;
    @Resource
    private DictService dictService;
    @Resource
    private BorrowerService borrowerService;
    @Autowired
    private LendService lendService;

    @Override
    public BigDecimal getBorrowAmount(Long userId) {
        // 查询借款人的积分
        UserInfo userInfo = userInfoMapper.selectById(userId);
        Integer integral = userInfo.getIntegral();
        // 查询积分表判断获取额度
        QueryWrapper<IntegralGrade> integralGradeQueryWrapper = new QueryWrapper<>();
        integralGradeQueryWrapper.gt("integral_end", integral)
                .le("integral_start", integral);
        IntegralGrade integralGrade = integralGradeMapper.selectOne(integralGradeQueryWrapper);
        BigDecimal borrowAmount = integralGrade.getBorrowAmount();
        if (ObjectUtils.isEmpty(integralGrade)) {
            return new BigDecimal(0);
        }
        // 返回数据
        return borrowAmount;
    }

    @Override
    public void saveBorrowInfo(BorrowInfo borrowInfo, Long userId) {
        //获取userInfo的用户数据
        UserInfo userInfo = userInfoMapper.selectById(userId);
        BorrowInfo borrowInfo1 = borrowInfoMapper.selectById(userInfo.getId());
        if (!ObjectUtils.isEmpty(borrowInfo1)) {
            BigDecimal borrowAmount = this.getBorrowAmount(userId);
            //存储数据
            //百分比转成小数
            borrowInfo1.setBorrowYearRate(borrowInfo1.getBorrowYearRate().divide(new BigDecimal(100)));
            borrowInfo1.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getStatus());
            borrowInfoMapper.updateById(borrowInfo1);
        }
        //判断借款额度是否足够
        BigDecimal borrowAmount = this.getBorrowAmount(userId);
        //存储数据
        borrowInfo.setUserId(userId);
        //百分比转成小数
        borrowInfo.setBorrowYearRate(borrowInfo.getBorrowYearRate().divide(new BigDecimal(100)));
        borrowInfo.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getStatus());
        borrowInfoMapper.insert(borrowInfo);
    }

    @Override
    public Integer getStatusByUserId(Long userId) {
        QueryWrapper<BorrowInfo> borrowInfoQueryWrapper = new QueryWrapper<>();
        borrowInfoQueryWrapper.select("status").eq("user_id", userId);
        // List<BorrowInfo> borrowInfoList = borrowInfoMapper.selectList(borrowInfoQueryWrapper);
        List<Object> objects = baseMapper.selectObjs(borrowInfoQueryWrapper);

        if (objects.size() == 0) {
            //借款人尚未提交信息
            return BorrowInfoStatusEnum.NO_AUTH.getStatus();
        }
        Integer status = (Integer) objects.get(0);

        // 返回数据
        return status;

    }

    @Override
    public List<BorrowInfo> selectBorrowInfoList() {
        ArrayList<BorrowInfo> arrayList = new ArrayList<>();
        BorrowInfo borrowInfo = null;
        HashMap<String, Object> map = null;
        List<BorrowInfo> borrowInfoList = borrowInfoMapper.selectList(null);
        for (BorrowInfo bif : borrowInfoList) {
            borrowInfo = new BorrowInfo();
            map = new HashMap<>();
            String returnMethod = dictService.getNameByParentDictCodeAndValue(DictEnum.RETURN_METHOD.getDictCode(), bif.getReturnMethod());
            String moneyUser = dictService.getNameByParentDictCodeAndValue(DictEnum.MONEY_USER.getDictCode(), bif.getMoneyUse());
            map.put("returnMethod", returnMethod);
            map.put("moneyUse", moneyUser);
            map.put("status", BorrowInfoStatusEnum.getMsgByStatus(bif.getStatus()));
            borrowInfo.setAmount(bif.getAmount());
            borrowInfo.setPeriod(bif.getPeriod());
            borrowInfo.setBorrowYearRate(bif.getBorrowYearRate());
            borrowInfo.setId(bif.getId());
            borrowInfo.setUserId(bif.getUserId());
            borrowInfo.setStatus(bif.getStatus());
            borrowInfo.setParam(map);
            log.info("查询借款人borrowInfoList列表---->>>" + borrowInfoList.toString());
            QueryWrapper<Borrower> borrowerQueryWrapper = new QueryWrapper<>();
            for (BorrowInfo info : borrowInfoList) {
                borrowerQueryWrapper.in("user_id", info.getUserId());
                List<Borrower> borrowerList = borrowerMapper.selectList(borrowerQueryWrapper);
                for (Borrower borrower : borrowerList) {
                    borrowInfo.setMobile(borrower.getMobile());
                    borrowInfo.setName(borrower.getName());
                    borrowInfo.setCreateTime(borrower.getCreateTime());
                }
            }
            arrayList.add(borrowInfo);
        }
        return arrayList;
    }

    @Override
    public Map<String, Object> showBorrowInfo(Long borrowInfoId) {
        HashMap<String, Object> map = new HashMap<>();
        // 借款信息封装
        BorrowInfo borrowInfo = borrowInfoMapper.selectById(borrowInfoId);
        String returnMethod = dictService.getNameByParentDictCodeAndValue(DictEnum.RETURN_METHOD.getDictCode(), borrowInfo.getReturnMethod());
        String moneyUser = dictService.getNameByParentDictCodeAndValue(DictEnum.MONEY_USER.getDictCode(), borrowInfo.getMoneyUse());
        borrowInfo.getParam().put("returnMethod", returnMethod);
        borrowInfo.getParam().put("moneyUse", moneyUser);
        borrowInfo.getParam().put("status", BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus()));
        map.put("borrowInfo", borrowInfo);

        // 借款人封装
        QueryWrapper<Borrower> borrowerQueryWrapper = new QueryWrapper<>();
        borrowerQueryWrapper.in("user_id", borrowInfo.getUserId());
        Borrower borrower = borrowerMapper.selectOne(borrowerQueryWrapper);
        BorrowerDetailVO borrowerDetailVO = borrowerService.getDetailByBorrowerId(borrower.getId());

        map.put("borrower", borrowerDetailVO);
        log.info("借款详情展示借款信息与借款人信息--->>>" + map);
        return map;
    }

    @Override
    public void approvalSubmit(BorrowInfoApprovalVO borrowInfoApprovalVO) {

        // 修改borrow_info的状态
        Long id = borrowInfoApprovalVO.getId();
        BorrowInfo borrowInfo = borrowInfoMapper.selectById(id);
        borrowInfo.setStatus(BorrowInfoStatusEnum.CHECK_OK.getStatus());
        borrowInfoMapper.updateById(borrowInfo);
        //审核通过后
        Integer borrowInfoApprovalVOStatus = borrowInfoApprovalVO.getStatus();
        Integer checkOkStatus = BorrowInfoStatusEnum.CHECK_OK.getStatus();
        // 创建标的lend
        if (borrowInfoApprovalVOStatus.equals(checkOkStatus)) {
            lendService.createLend(borrowInfoApprovalVO, borrowInfo);
        }


    }
}
